package com.sundablog.service.impl.systemsetup.basicsetup.upload;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sundablog.fastdfs.FastdfsClient;
import com.sundablog.service.systemsetup.basicsetup.upload.UploadService;

import cn.hutool.core.util.RandomUtil;


@Service
public class UploadServiceImpl implements UploadService {

	/**
	 * fastdfs图片服务器地址
	 */
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;

	/**
	 * 图片上传模式选择 1本地分布式 2.7牛云 3.阿里云 4.本地
	 */
	@Value("${UPLOADING_QINIU_TYPE}")
	private int UPLOADING_QINIU_TYPE;

	/**
	 * 7牛云 ACCESSKE
	 */
	@Value("${UPLOADING_QINIU_ACCESSKE}")
	private String UPLOADING_QINIU_ACCESSKE;

	/**
	 * 7牛云 SECRETKEY
	 */
	@Value("${UPLOADING_QINIU_SECRETKEY}")
	private String UPLOADING_QINIU_SECRETKEY;

	/**
	 * 7牛云 QINIU_BUCKET
	 */
	@Value("${UPLOADING_QINIU_BUCKET}")
	private String UPLOADING_QINIU_BUCKET;

	/**
	 * 7牛云 SERVER_URL
	 */
	@Value("${UPLOADING_QINIU_SERVER_URL}")
	private String UPLOADING_QINIU_SERVER_URL;

	/**
	 * 阿里云 ENDPOINT
	 */
	@Value("${UPLOADING_ALIYUN_ENDPOINT}")
	private String UPLOADING_ALIYUN_ENDPOINT;

	/**
	 * 阿里云 ACCESSKEYID
	 */
	@Value("${UPLOADING_ALIYUN_ACCESSKEYID}")
	private String UPLOADING_ALIYUN_ACCESSKEYID;

	/**
	 * 阿里云 ACCESSKEYSECRET
	 */
	@Value("${UPLOADING_ALIYUN_ACCESSKEYSECRET}")
	private String UPLOADING_ALIYUN_ACCESSKEYSECRET;

	/**
	 * 阿里云 BUCKETNAME
	 */
	@Value("${UPLOADING_ALIYUN_BUCKETNAME}")
	private String UPLOADING_ALIYUN_BUCKETNAME;

	/**
	 * 本地上传路径
	 */
	@Value("${UPLOADING_LOCAL_PATH}")
	private String UPLOADING_LOCAL_PATH;
	
	@Value("${UPLOADING_LOCAL_URL}")
	private String UPLOADING_LOCAL_URL;
	
	
	/**
	 * 本地文件上传
	 * @Title: LocalUpload   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param filContent
	 * @param: @param extName
	 * @param: @return      
	 * @return: Map<String,String>      
	 * @throws
	 */
	private Map<String, String> LocalUpload(byte[] filContent, String extName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(UPLOADING_LOCAL_PATH);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			String name = RandomUtil.randomUUID() +".jpg";
			file = new File(UPLOADING_LOCAL_PATH + "\\" + name);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(filContent);
			Map<String, String> map = new HashMap<>();
			map.put("route", name);
			map.put("fullPath", UPLOADING_LOCAL_URL+name);
			return map;
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 本地分布式上传
	 * @Title: LocalFastdfsUpload   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param filContent
	 * @param: @param extName
	 * @param: @return      
	 * @return: Map<String,String>      
	 * @throws
	 */
	private Map<String, String> LocalFastdfsUpload(byte[] filContent, String extName) {
		try {
			FastdfsClient fastdfsClient = new FastdfsClient("classpath:config/fastdfsClient.conf");
			String route = fastdfsClient.uploadFile(filContent, extName);
			String fullPath = IMAGE_SERVER_URL + route;
			Map<String, String> map = new HashMap<>();
			map.put("route", route);
			map.put("fullPath", fullPath);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 阿里云上传
	 * @Title: UploadAliYun   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param filContent
	 * @param: @param extName
	 * @param: @return      
	 * @return: Map<String,String>      
	 * @throws
	 */
	private Map<String, String> UploadAliYun(byte[] filContent, String extName) {
		OSSClient ossClient = new OSSClient(UPLOADING_ALIYUN_ENDPOINT, UPLOADING_ALIYUN_ACCESSKEYID,
				UPLOADING_ALIYUN_ACCESSKEYSECRET);
		try {
			ossClient.putObject("sundablogtest", "123/1234.jpg", new ByteArrayInputStream(filContent));
			ossClient.shutdown();
			Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
			// 获取URL
			URL url = ossClient.generatePresignedUrl("sundablogtest", "1234.jpg", expiration);
			Map<String, String> map = new HashMap<>();
			map.put("route", "200");
			map.put("fullPath", url.toString());
			return map;
		} catch (Exception e) {
			System.err.println("错误");
			return null;
		}
	}

	/**
	 * 7牛文件上传
	 * @Title: QinIuUpload   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param filContent
	 * @param: @param extName
	 * @param: @return      
	 * @return: Map<String,String>      
	 * @throws
	 */
	private Map<String, String> QinIuUpload(byte[] filContent, String extName) {
		Configuration cfg = new Configuration(Zone.zone2());
		UploadManager uploadManager = new UploadManager(cfg);
		Auth auth = Auth.create(UPLOADING_QINIU_ACCESSKE, UPLOADING_QINIU_SECRETKEY);
		String upToken = auth.uploadToken(UPLOADING_QINIU_BUCKET);
		try {
			Response response = uploadManager.put(filContent, RandomUtil.randomUUID(), upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			String fullPath = UPLOADING_QINIU_SERVER_URL + putRet.key;
			Map<String, String> map = new HashMap<>();
			map.put("route", putRet.key);
			map.put("fullPath", fullPath);
			return map;
		} catch (QiniuException e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * layUI文件上传 Title: fileUploadLayui Description:
	 * 
	 * @param filContent
	 * @param extName
	 * @return
	 * @see com.sundablog.service.systemsetup.basicsetup.upload.UploadService#fileUploadLayui(byte[],
	 *      java.lang.String)
	 */
	@Override
	public Map<String, String> fileUploadLayui(byte[] filContent, String extName) {
		Map<String, String> map = null;
		if (1 == UPLOADING_QINIU_TYPE) {
			map = LocalFastdfsUpload(filContent, extName);
		} else if (2 == UPLOADING_QINIU_TYPE) {
			map = QinIuUpload(filContent, extName);
		} else if (3 == UPLOADING_QINIU_TYPE) {
			map = UploadAliYun(filContent, extName);
		} else if (4 == UPLOADING_QINIU_TYPE) {
			map = LocalUpload(filContent,extName);
		}
		return map;
	}

}
